package my.data.x.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

public class XException extends RuntimeException  {
    private ErrorCode errorCode;

    public XException(ErrorCode errorCode,String errorMessage){
        super(errorCode.toString()+" \r\n ===> "+errorMessage);
        this.errorCode=errorCode;
    }

    public XException(ErrorCode errorCode,String errorMessage,Throwable cause){
        super(errorCode.toString() + " \r\n ===> " + errorMessage + " \r\n ---> " + getMessage(cause), cause);
        this.errorCode = errorCode;
    }
    public static XException asXException(ErrorCode errorCode,String message){
        return new XException(errorCode,message);
    }
    public static XException asXException(ErrorCode errorCode, Throwable cause) {
        if (cause instanceof XException) {
            return (XException) cause;
        }
        return new XException(errorCode, getMessage(cause), cause);
    }

    public String getErrorCodeCode(){
        return errorCode.getCode();
    }
    private static String getMessage(Object obj) {
        if (obj == null) {
            return "__message is null__";
        }
        if (obj instanceof Throwable) {
            StringWriter str = new StringWriter();
            PrintWriter pw = new PrintWriter(str);
            ((Throwable) obj).printStackTrace(pw);
            return str.toString();
        } else {
            return obj.toString();
        }
    }
}
